package com.acoffee.web;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @author acoffee
 * @create 2021-10-28 19:23
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        StringBuffer url = req.getRequestURL();
        String methodName = url.substring(url.lastIndexOf("/") + 1);

        Class clazz = this.getClass();
        try {
            Object obj = clazz.newInstance();
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(obj, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("servlet的方法执行失败！");
        }
    }

    public void response(HttpServletResponse resp, Object obj) {
        resp.setContentType("text/html;charset=utf-8");
        ObjectMapper om = new ObjectMapper();
        try {
            om.writeValue(resp.getWriter(), obj);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
